using UnityEngine;
using System.Collections;

public class SpriteAnimation : MonoBehaviour {
	
	public delegate void OnSpriteAnimEvents();
	public event OnSpriteAnimEvents onStopPlayOnce;
	
	public float repeatAnimDelay;
	float delayStartTime;
	
	public Material matAnim;
	public float minFrameLimit;
	public float maxFrameLimit;
	
	public float currentFrame;
	
	public float speed;
	
	float timeStart;
	
	public bool isPLaying;
	
	public void PlayMe()
	{
		AnimateMe();
	}
	
	public void StopMe()
	{
		timeStart = 0.0f;
		currentFrame = 0.0f;
		//matAnim.SetTextureOffset("_MainTex", new Vector2(0,0));
	}
	
	void AnimateMe()
	{
		if(timeStart  > speed)
		{
			timeStart = 0.0f;
			
			matAnim.SetTextureOffset("_MainTex", new Vector2(currentFrame / maxFrameLimit,0));
			//Debug.Log(currentFrame / maxFrameLimit);
			
			currentFrame++;
			if(currentFrame > maxFrameLimit)
				currentFrame = minFrameLimit;
		}

		timeStart += Time.deltaTime;
	}
	
	public void PlayMeOnce()
	{
		if(!isPlayingRightNow)
			StartCoroutine("AnimateMeOnce");
	}
	
	public bool isPlayingRightNow;
	IEnumerator AnimateMeOnce()
	{
		currentFrame = 0;
		isPLaying = true;
		while(isPLaying)
		{
			if(timeStart  > speed)
			{
				matAnim.SetTextureOffset("_MainTex", new Vector2((float)currentFrame / (float)maxFrameLimit,0));
				//Debug.Log((float)currentFrame / (float)maxFrameLimit);
				
				isPlayingRightNow = true;
				timeStart = 0.0f;
				currentFrame++;
				
				if(currentFrame >= maxFrameLimit)
				{
					currentFrame = minFrameLimit;
					isPlayingRightNow = false;
					if(onStopPlayOnce != null)	onStopPlayOnce();
					yield break;
				}
			}
						
			timeStart += Time.deltaTime;
			yield return 0;
		}
	}
}
